<?php
/**
 * @用户登陆类,不受限制.
 * @author cenchy
 **/
class UserLoginAction extends Action{

	private $userM;

	private $snkey;
	private $cookiename;
	private $loginUrl;
	private $logoutUrl;
	private $loginMainUrl;
	private $AppUrl;

	public function _initialize(){
		$this->userM = D('User');//用户model

		$this->snkey = C('COOKIE_LOGIN_SNKEY');
		$this->cookiename = C('COOKIE_LOGIN_NAME');
		$this->loginUrl = U('User-UserLogin/login');//登录接口
		$this->logoutUrl = U('User-UserLogin/logout');//登出接口
		$this->loginMainUrl = U('User-UserLogin/index');//登陆页面
		$this->AppUrl = U('Home-Index/index');//主页面
	}

	public function index(){
		if($this->UserId){
			$UserObject = $this->userM->getObject($this->UserId);
		}
		if(isset($UserObject)){
			$this->assign('UserClass',$UserObject);
			$this->assign('isLogin',1);
		}else{
			$this->assign('isLogin',0);
		}
		$this->assign('loginstr','登陆页面');
		$this->assign('UserId',$this->UserId);
		$this->assign('loginUrl',$this->loginUrl);
		$this->assign('logoutUrl',$this->logoutUrl);
		$this->assign('AppUrl',$this->AppUrl);
		$this->display();
	}

	public function login(){
		$CurrentTime = SYSTEM_TIME;
		$username = $_POST['username'];
		$password = $_POST['password'];
		$condition['UserName'] = $username;
		$user=$this->userM->where($condition)->find();
		if($user['Id']){
			if($user['PassWord']!==md5($password)){
				redirect($this->loginMainUrl,2,'<center>密码错误</center>');
			}
		}else{
			redirect($this->loginMainUrl,2,'<center>账号错误</center>');
		}
		$userip = get_client_ip();
		$randomstr = mt_rand(100,999);
		$keystr = $user['Id'].$user['UserName'].$userip.$randomstr.$CurrentTime.$this->snkey;
		$md5Str = md5($keystr);
		if($user){
			$updateUser['LoginKey'] = $md5Str;
			$updateUser['LoginTime'] = $CurrentTime;
			$updateUser['Id'] = $user['Id'];
			$cookievalue = $user['Id'].'|'.$user['UserName'].'|'.$md5Str;
			if($this->userM->saveObject($updateUser)){
				cookie($this->cookiename,$cookievalue,0);
				redirect($this->AppUrl,1,'<center>登录成功</center>');
			}
		}else{
			redirect($this->loginMainUrl,2,'<center>登录失败</center>');
		}
	}

	public function logout(){
		cookie($this->cookiename,null);
		redirect($this->loginMainUrl);

	}
}
?>
